import streamlit as st
import pandas as pd
import plotly.express as px
import plotly.graph_objects as go
from datetime import datetime, timedelta

class DashboardView:
    """仪表板视图类"""
    
    def __init__(self):
        pass
    
    def render(self):
        """渲染Dashboard页面"""
        st.markdown("<h1 class='main-header'> EmlAIdata 邮件处理监控面板</h1>", unsafe_allow_html=True)
        
        # 状态指标行
        metric_cols = st.columns(4)
        with metric_cols[0]:
            st.metric(
                label="处理状态", 
                value="运行中" if st.session_state.is_processing else "已停止",
                delta="活跃" if st.session_state.is_processing else "暂停",
                delta_color="normal"
            )

        with metric_cols[1]:
            delta_val = st.session_state.email_stats['processed_count'] - st.session_state.email_stats['last_processed']
            st.metric(
                label="已处理邮件", 
                value=st.session_state.email_stats['processed_count'],
                delta=f"+{delta_val}" if delta_val > 0 else None
            )
            st.session_state.email_stats['last_processed'] = st.session_state.email_stats['processed_count']

        with metric_cols[2]:
            st.metric(
                label="剩余邮件", 
                value=st.session_state.email_stats['remaining_count']
            )

        with metric_cols[3]:
            st.metric(
                label="成功数量", 
                value=st.session_state.email_stats['success_count']
            )
        
        # 统计图表
        st.subheader("处理统计")
        chart_cols = st.columns([2, 1])
        
        with chart_cols[0]:
            # 处理历史折线图
            if st.session_state.email_stats['history']:
                history_df = pd.DataFrame(st.session_state.email_stats['history'])
                
                history_df['timestamp'] = pd.to_datetime(history_df['timestamp'], format='%Y-%m-%d %H:%M:%S', errors='coerce')
                # 添加时间聚合选项
                col1, col2 = st.columns([3, 1])
                with col2:
                    time_granularity = st.selectbox(
                        "时间粒度",
                        options=["原始数据", "5分钟", "15分钟", "1小时", "1天"],
                        index=1
                    )
                
                # 根据选择的粒度聚合数据
                if time_granularity != "原始数据":
                    freq_map = {
                        "5分钟": "5min",
                        "15分钟": "15min", 
                        "1小时": "1H",
                        "1天": "1D"
                    }
                    freq = freq_map[time_granularity]
                    
                    # 按时间间隔聚合数据
                    history_df = history_df.set_index('timestamp')
                    
                    # 添加数据验证：移除NaT值和无效数据
                    history_df = history_df.dropna()  # 移除包含NaT的行
                    
                    # 检查是否还有有效数据
                    if history_df.empty:
                        st.warning("⚠️ 时间数据无效，无法生成图表")
                        plot_df = pd.DataFrame()  # 空DataFrame
                    else:
                        try:
                            aggregated_df = history_df.resample(freq).agg({
                                'processed': 'sum',
                                'success': 'sum', 
                                'error': 'sum'
                            }).reset_index()
                            
                            # 过滤掉全为0的行
                            aggregated_df = aggregated_df[
                                (aggregated_df['processed'] > 0) | 
                                (aggregated_df['success'] > 0) | 
                                (aggregated_df['error'] > 0)
                            ]
                            
                            plot_df = aggregated_df
                        except Exception as e:
                            st.error(f"❌ 数据聚合失败：{str(e)}")
                            plot_df = pd.DataFrame()  # 空DataFrame
                else:
                    # 原始数据也需要验证
                    history_df = history_df.dropna(subset=['timestamp'])
                    plot_df = history_df

                # 只有在有有效数据时才绘制图表
                with col1:
                    if not plot_df.empty:
                        fig = px.line(
                            plot_df, 
                            x='timestamp', 
                            y=['processed', 'success', 'error'],
                            labels={'value': '邮件数量', 'timestamp': '时间', 'variable': '类型'},
                            color_discrete_map={
                                'processed': '#3498db', 
                                'success': '#2ecc71', 
                                'error': '#e74c3c'
                            },
                            title=f"邮件处理历史 ({time_granularity})"
                        )
                        fig.update_layout(
                            legend_title_text='',
                            hovermode="x unified",
                            legend=dict(orientation="h", yanchor="bottom", y=1.02, xanchor="right", x=1),
                            margin=dict(l=20, r=20, t=40, b=20),
                            xaxis=dict(
                                tickformat='%Y-%m-%d %H:%M:%S' if time_granularity == "原始数据" else 
                                          '%Y-%m-%d %H:%M' if time_granularity in ["5分钟", "15分钟"] else
                                        '%Y-%m-%d %H'if time_granularity == "1小时" else '%Y-%m-%d',
                                tickangle=45,
                                dtick={
                                    "原始数据": 60000,      # 1分钟间隔（毫秒）
                                    "5分钟": 300000,        # 5分钟间隔
                                    "15分钟": 900000,       # 15分钟间隔
                                    "1小时": 3600000,       # 1小时间隔
                                    "1天": 86400000         # 1天间隔
                                }.get(time_granularity, 300000)  # 默认5分钟
                            )
                        )
                        st.plotly_chart(fig, use_container_width=True)
                    else:
                        st.info("📊 暂无有效的历史数据可显示")
            else:
                st.info("暂无处理历史数据")
        
        with chart_cols[1]:
            # 处理结果扇形图
            if st.session_state.email_stats['processed_count'] > 0:
                fig = go.Figure(data=[go.Pie(
                    labels=['成功', '失败'],
                    values=[st.session_state.email_stats['success_count'], 
                            st.session_state.email_stats['error_count']],
                    hole=.4,
                    marker_colors=['#2ecc71', '#e74c3c']
                )])
                fig.update_layout(
                    title_text="处理结果分布",
                    annotations=[dict(text=f"总计<br>{st.session_state.email_stats['processed_count']}", 
                                    x=0.5, y=0.5, font_size=15, showarrow=False)],
                    margin=dict(l=20, r=20, t=40, b=20),
                )
                st.plotly_chart(fig, use_container_width=True)
            else:
                st.info("暂无处理结果数据")